<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Models\Operator;
use App\Models\Machine;
use App\Models\MachineManager;
use App\Models\Merchant;
use App\Models\Role;
use App\Models\Auth;
use App\Http\Requests\Admin\AdminUserRequest;

class OperatorController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, Operator $operator)
    {
        $manager = auth('admin')->user();
        $operator = $operator->with('merchant');
        if($manager->type == 3){
            $operator = $operator->where(['parent_id' => $manager->id]);
        }
        $admin_users = $operator->filter($request->all())->orderBy('id', 'desc')->paginate(config('api.page.limit'));
        $name = $request->name;
        $phone = $request->phone;
        return view('admins.operator.index',compact('admin_users','name', 'phone'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Operator $operator)
    {
        return view('admins.operator.add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(AdminUserRequest $request, Operator $operator)
    {
        $result = $operator->create($request->all());
        if(!$result){
            return back()->with('warning','添加失败');
        }
        return redirect()->route('admin.operators.index')->with('success', '添加成功');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Operator $operator)
    {
        return view('admins.operator.edit', compact('operator'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(AdminUserRequest $request, Operator $operator)
    {
        $result = $operator->update($request->all());
        if(!$result){
            return back()->with('warning','编辑失败');
        }
        return redirect()->route('admin.operators.index')->with('success', '编辑成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    // public function destroy(Operator $operator)
    // {
    //     dd($operator);
    // }
    public function delete(Request $request, Auth $auth, Operator $operator)
    {
        $manager = $auth->where('parent_id', $request->id)->first();
        $operator = $operator->with('machine')->find($request->id);
        if($operator->machine->isNotEmpty() || $manager){
            return json_encode(['code' => 400, 'message' => '该账号下存在下级账户或设备,请移除后再删除']);
        }
        $operator->delete();
        return json_encode(['code' => 200, 'message' => '删除成功']);
    }
    //分配设备
    public function allocation(Operator $operator)
    {
        return view('admins.operator.allocation', compact('operator'));
    }
    //
    public function allocationStore(Request $request, Operator $operator)
    {
        $operator = $operator->find($request->operator_id);
        if(!$request->machines){
            $res = optional($operator)->machine()->detach();
            return redirect()->route('admin.operators.index')->with('success', '编辑成功');
        }
        $machine_ids = explode(',', $request->machines);
        $machine_manager_data = [];
        foreach ($machine_ids as $key => $value) {
            $machine_manager_data[$value] = ['type' => $operator->type, 'percentage' => 0.06];
        }
        $res = optional($operator)->machine()->sync($machine_manager_data);
        if(empty($res['attached'])){
            return redirect()->route('admin.operators.index')->with('warning','编辑失败'); 
        }
        return redirect()->route('admin.operators.index')->with('success', '编辑成功');
    }
    //获取设备
    public function machines(Request $request,Merchant $merchant, Operator $operator, Machine $machine, MachineManager $machine_manager)
    {
        $manager = auth('admin')->user();
        $operator = $operator->find($request->operator_id);
        $merchant = $merchant->with('machine')->find($operator->parent_id); 
        $machines = optional($merchant)->machine;
        $operator_id = $request->operator_id;
        $manager_machines = $machine_manager->where('manager_id',$operator_id)->get();
        $operator_machines = $manager_machines->pluck('machine_id');
        return json_encode(['code' => 200, 'msg' => 'success', 'data' => compact('machines', 'operator_machines')]);

    }
    public function setRole(Operator $operator)
    {
        return view('admins.operator.setroles', compact('operator'));
    }
    /**
     * [分配角色 description]
     * @param Request    $request    [description]
     * @param Role       $role       [description]
     * @param Permission $permission [description]
     */
    public function setRoleStore(Request $request, Role $role, Auth $operator)
    {   
        $operator_id = $request->operator_id;
        $operator = $operator->with('roles')->find($operator_id);
        $roles = $request->roles;
        if(!$roles){
            optional($operator)->roles()->detach();   
        }else{
            $res =  optional($operator)->assignRole(explode(',', $roles)); 
        }               
        return redirect()->route('admin.operators.index')->with('success', '编辑成功');
    }

    public function getRoles(Request $request, Role $role, Auth $operator)
    {
        $operator_id = $request->operator_id;
        $operator = $operator->with('roles')->find($operator_id);
        $roles = $role->get();
        $operator_roles = optional($operator)->roles;        
        $operator_roles = $operator_roles->pluck('id');
        return json_encode(['code' => 200, 'msg' => 'success', 'data' => compact('operator_roles','roles')]);
    }
    //重置密码
    public function resetPassword(Request $request, Operator $operator)
    {
        $operator = $operator->find($request->id);
        $operator->password = encrypt_str('123456');
        $res = $operator->save();
        return json_encode(['code' => 200, 'msg' => 'success', 'data' => $res]);
    }

    public function lists(Request $request, Operator $operator)
    {
        $user = auth('admin')->user();     
        if($user->type == 3){
            $operator = $operator->where('parent_id', $user->id);
        }   
        $operator = $operator->orderBy('id', 'desc')->get();
        return json_encode(['code' => 200, 'msg' => 'success', 'data' => $operator]);
    }
}
